package cn.sprouting.tool;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 随机密码相关
 *
 * @author ：LX（长沙麓谷）
 * @date 创建时间： 2021/11/5 11:37
 */
public class RandomPasswordTool {

    /**
     * 常用特殊字符
     */
    public static List<String> SPECIAL_CHAR_LIST = CollUtil.newArrayList("!", ".", "_", "@", "#", "$", "%", "^", "&", ",", "(", ")", "`", "[", "]", "*");




    /**
     * 随机生成强密码
     * @param length 密码长度
     * @param useSpecialChar 是否添加特殊字符
     * @return
     */
    public static String getPassword(int length, boolean useSpecialChar){
        if (length < 8) {
            //至少8位
            length = 8;
        }
        List<String> pwd = new ArrayList<>();
        //最多1/3的大写字母和小写字母
        int oneThirdCount = length / 3;
        for (int i = 0; i < oneThirdCount; i++) {
            pwd.add(RandomUtil.randomString(RandomUtil.BASE_CHAR, 1).toUpperCase());
            pwd.add(RandomUtil.randomString(RandomUtil.BASE_CHAR, 1).toLowerCase());
        }

        //特殊字符
        if (useSpecialChar) {
            int b = RandomUtil.randomInt(1, oneThirdCount);
            if (b > 0) {
                pwd.addAll(RandomUtil.randomEleList(SPECIAL_CHAR_LIST, b));
            }
        }

        //剩下不足的用数字填充
        if (pwd.size() < length) {
            int digitCount = length - pwd.size();
            pwd.add(RandomUtil.randomString(RandomUtil.BASE_NUMBER, digitCount));
        }

        //打乱顺序
        Collections.shuffle(pwd);
        return StrUtil.join("", pwd);
    }

}
